package com.pactera.redisrelated.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
@Slf4j
public class RedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public final static String REDIS_KEY = "ranklist";

    /**
     * 排行榜
     */
    public void rank(){
        Set<ZSetOperations.TypedTuple<String>> tuples = new HashSet<>();
        for (int i = 0; i < 100000; i++) {
            DefaultTypedTuple<String> tuple = new DefaultTypedTuple<>("lisa" + i, 1D + i);
            tuples.add(tuple);
        }
        redisTemplate.opsForZSet().add(REDIS_KEY, tuples);


        int topNum = 10;
        Set<String> range = redisTemplate.opsForZSet().reverseRange(REDIS_KEY, 0, topNum);
        log.info("前{}名为：{}", topNum, range);
        Set<ZSetOperations.TypedTuple<String>> rangeWithScores = redisTemplate.opsForZSet().reverseRangeWithScores(REDIS_KEY, 0, topNum);
        log.info("前{}名为：{}", topNum, rangeWithScores);
    }

}
